package com.shujia.spark.stream

import org.apache.spark.SparkContext
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo4DStreamToRDD {
  def main(args: Array[String]): Unit = {

    val spark: SparkSession = SparkSession
      .builder()
      .master("local[2]")
      .appName("rdd")
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    val sc: SparkContext = spark.sparkContext


    val ssc = new StreamingContext(sc, Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
     * DStream: 每个一点时间将接收到的数据封装成一个rdd
     * foreachRDD: 将DStream转换成rdd,每个一段时间一个
     */

    linesDS.foreachRDD(rdd => {
      //使用rdd api 处理数据
      rdd
        .flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)
        .foreach(println)

      /**
       * 将rdd转换成df使用 sql 或者dsl处理数据
       */
      val linesDF: DataFrame = rdd.toDF("line")
      //dsl
      linesDF
        .select(explode(split($"line", ",")) as "word")
        .groupBy($"word")
        .agg(count($"word") as "count")
        .show()

      linesDF.createOrReplaceTempView("lines")

      //sql
      spark.sql(
        """
          |select word,count(1) as count from (
          |select explode(split(line,',')) as word
          |from
          |lines
          |) as a
          |group by word
          |
          |
          |""".stripMargin)
        .show()


    })

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()


  }

}
